package com.apes.fn.scm.appScan;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productReceive.ProductReceive;
import com.apes.fn.server.productReceive.ProductReceiveItem;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.fn.server.servicePlan.service.ServicePlanceService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 配件领用
 */
@Component
public class ProductReceiveTemplate extends SimpleTemplate {

    @Autowired
    private ServicePlanItemRepository servicePlanItemRepository;
    @Autowired
    private ProductAccountService productAccountService;
    @Autowired
    private LocationRepository locationRepository;

    @Override
    public String[] identifys() {
        return new String[]{"LY0"};
    }

    @Override
    public JSONArray getOrderLists(SimpleRequest request, String origin) {
        JSONObject json = request.getJO();
        String locationId = json.getString("locationId");

        if (origin == null) {  // 查询服务单可配件领用单据
            List<String> deptIds = getOperatorDept(request);    // 获取可操作部门
            List<ServicePlan> servicePlans = SpringManager.getBean(ServicePlanceService.class).findServicePlansForPDA(deptIds);
            return servicePlans.stream().map(this::getOrderJO).collect(Collectors.toCollection(JSONArray::new));
        } else if (locationId != null && origin != null) { // 查询商品明细
            return servicePlanItemRepository.findServicePlanItemsForPDA(origin, locationId).stream()
                    .map(this::getOrderItemJO).collect(Collectors.toCollection(JSONArray::new));
        } else { // 查询库存信息
            return servicePlanItemRepository.findAll(JpaDsl.toCriteriaByEq("servicePlan.id", origin)).stream().map(
                    item -> {
                        JSONObject result = new JSONObject();
                        result.put("CKKQID", item.getLocation().getId());
                        result.put("CKKQMC", item.getLocation().getName());
                        result.put("CKID", item.getLocation().getPhyDepot() != null ? item.getLocation().getPhyDepot().getId() : null);
                        result.put("CKMC", item.getLocation().getPhyDepot() != null ? item.getLocation().getPhyDepot().getName() : null);
                        result.put("KQID", item.getLocation().getUsage().getId());
                        result.put("KQMC", item.getLocation().getUsage().getName());
                        result.put("FWDH", item.getServicePlan().getId());
                        result.put("FWFAH", item.getId());
                        return result;
                    }
            ).collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getString("CKKQID")))), ArrayList::new)
            ).stream().collect(Collectors.toCollection(JSONArray::new));
        }

    }

    private JSONObject getOrderJO(ServicePlan servicePlan) {
        JSONObject result = new JSONObject();
        result.put("FWDH", servicePlan.getId());
        if (servicePlan.getFnCustomerExpand() != null) {
            result.put("CPHM", servicePlan.getFnCustomerExpand().getCarLicense());
        }
        result.put("MDID", servicePlan.getSaleDept().getId());
        result.put("MDMC", servicePlan.getSaleDept().getName());
        result.put("FWMDID", servicePlan.getServiceDept().getId());
        result.put("FWMDMC", servicePlan.getServiceDept().getName());
        result.put("DSB", result.getString("FWDH") + "-" + result.getString("CPHM"));
        return result;
    }

    private JSONObject getOrderItemJO(ServicePlanItem servicePlanItem) {
        JSONObject result = new JSONObject();
        result.put("SMJS", 0);
        result.put("YLYJS", servicePlanItem.getSaleQty());
        result.put("YLYSL", servicePlanItem.getSaleQty());
        result.put("DJSL", servicePlanItem.getSaleQty() - servicePlanItem.getQtyReceive() - servicePlanItem.getQtyEnd());
        result.put("FWDH", servicePlanItem.getServicePlan().getId());
        result.put("FABH", servicePlanItem.getId());

        result.put("SPID", servicePlanItem.getProduct().getId());
        result.put("SPMC", servicePlanItem.getProduct().getName());
        result.put("CKID", servicePlanItem.getLocation().getPhyDepot() != null ? servicePlanItem.getLocation().getPhyDepot().getId() : null);
        result.put("CKMC", servicePlanItem.getLocation().getPhyDepot() != null ? servicePlanItem.getLocation().getPhyDepot().getName() : null);
        result.put("CKKQID", servicePlanItem.getLocation().getId());
        result.put("CKKQMC", servicePlanItem.getLocation().getName());
        result.put("KQID", servicePlanItem.getLocation().getUsage().getName());
        result.put("KQMC", servicePlanItem.getLocation().getUsage().getName());
        result.put("JLDW", servicePlanItem.getUom().getName());
        result.put("GYSID", "G1001");
        result.put("GYSMC", "广州市集群车宝汽车服务连锁有限公司");
        result.put("CGZZID", "1001");
        result.put("CGZZMC", "广州市集群车宝汽车服务连锁有限公司");
        result.put("SPZID", servicePlanItem.getProduct().getProductGroup().getId());
        result.put("SPZMC", servicePlanItem.getProduct().getProductGroup().getName());
        result.put("SSBL", servicePlanItem.getProduct().getTax().getAmt());
        result.put("GYSTM", servicePlanItem.getProduct().getBarcode());
        result.put("GSID", servicePlanItem.getServicePlan().getCompany().getId());
        result.put("GSMC", servicePlanItem.getServicePlan().getCompany().getName());
        result.put("SPSX", 0);

        result.put("HSBL", servicePlanItem.getProduct().getUom().getFactor());
        result.put("XSJS", servicePlanItem.getSaleQty());
        result.put("XSSL", servicePlanItem.getSaleQty());

        Map map = productAccountService.getUomUsableQty(servicePlanItem.getLocation(), servicePlanItem.getProduct(), servicePlanItem.getUom(), servicePlanItem.getLocation().getCompany());
        result.put("MDKYS", map.isEmpty() ? 0.0 : map.get("marketableQty"));
        return result;
    }

    @Override
    public void submit(SimpleRequest request) {
        String locationId = request.get("CKKQID");
        ProductReceive productReceive = new ProductReceive();
        productReceive.setReceiver(getCreator(request));
        Location location = locationRepository.findOne(locationId);
        productReceive.setLocation(location);
        productReceive.setSource(request.get("FWDH"));
        productReceive.setSourceBusinessType("ServicePlan");
        productReceive.setSourceBusinessTypeName("服务方案");
        productReceive.setScanSign(true); //设置扫码标记
        productReceive.setRemark("扫码端领用");
        productReceive.setState("create");
        productReceive.setProductReceiveItems(((JSONArray) request.get("WAR_TMCRKDMX")).stream().map(ly -> {
            JSONObject receive = (JSONObject) ly;
            ProductReceiveItem productReceiveItem = new ProductReceiveItem();
            productReceiveItem.setCompany(SpringManager.getBean(PartyRoleRepository.class).findOne((receive.getString("GSID"))));
            productReceive.setCompany(productReceiveItem.getCompany());
            productReceiveItem.setProduct(getProduct(receive.getString("SPID")));
            productReceiveItem.setUom(productReceiveItem.getProduct().getUom());
            productReceiveItem.setQtyReceive(receive.getDouble("SMJS") * receive.getDouble("HSBL"));

            // 与原服务方案明细做关联
            ServicePlanItem servicePlanItem = new ServicePlanItem();
            servicePlanItem.setId(receive.getString("FABH"));
            productReceiveItem.setServicePlanItem(servicePlanItem);
            return productReceiveItem;
        }).collect(Collectors.toList()));
        productReceive.setWrite(false);
        ProductReceive receive = invoke("stock.productReceive.create", MapUtil.mapped(productReceive));
        User user = SpringManager.getBean(UserRepository.class).findByPartyRole(receive.getReceiver()).stream().findAny().orElse(null);
        SimpleSession session = request.getSession();
        String workPostName = session != null ? session.getAttribute("workPostName", String.class) : null;
        if (user!=null){
            Integer id = user.getId();
            addProductReceiveLogger(receive,"保存",id+"", workPostName);
        }else {
            addProductReceiveLogger(receive,"保存", session != null ? session.getUserId() : null, workPostName);
        }

        productReceive.setWrite(false);
        receive = invoke("stock.productReceive.approve", MapUtil.mapped(receive));
        if (user!=null){
            Integer id = user.getId();
            addProductReceiveLogger(receive,"审核",id+"", workPostName);
        }else {
            addProductReceiveLogger(receive,"审核", session != null ? session.getUserId() : null, workPostName);
        }

    }
    public void addProductReceiveLogger(ProductReceive receive,String operate,String userId,String workPostName){
        SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                "businessType", receive.getInnerBusinessType(),
                "businessKey", receive.getInnerBusinessKey(),
                "operate", operate,
                "workPostName", workPostName,
                "audit", receive.getAudit(),
                "operator_id", userId
        ));
    }
}
